<template>
  <BasicModal
    v-bind="$attrs"
    :title="t('common.create') + dataValue"
    @register="register"
    @ok="handleSubmit"
    @cancel="handleCancel"
    :destroyOnClose="true"
    :minHeight="450"
    :width="1200"
  >
    <Tabs v-model:activeKey="detailActiveKey">
      <TabPane key="1" :tab="t('routes.demo.documentManager.property')">
        <BasicForm @register="registerForm" />
      </TabPane>
      <TabPane key="2" :tab="t('routes.demo.documentManager.attachment')">
        {{ uploadFileText }}
        <!-- 上传文件框 -->
        <UploadDragger :multiple="true" name="file" :customRequest="customUpload">
          <p class="ant-upload-drag-icon"></p>
          <p class="ant-upload-text">{{ t('routes.demo.documentWorkPlace.dropFilesHere') }}</p>
          <p class="ant-upload-hint">{{
            t('routes.demo.documentWorkPlace.supportSingleOrBatchUpload')
          }}</p>
        </UploadDragger>
      </TabPane>
      <TabPane key="3" :tab="t('routes.demo.documentManager.associated')">
        <BasicTable @register="registerAssociation" :dataSource="fileAssociationList">
          <template #toolbar>
            <a-button type="primary" @click="handleAssociated">
              {{ t('routes.demo.documentManager.associatedObject') }}
            </a-button>
          </template>
        </BasicTable>
      </TabPane>
      <TabPane key="4" :tab="t('routes.demo.documentManager.reverseAssociated')">
        <BasicTable @register="registerBeAssociation" />
      </TabPane>
    </Tabs>
    <!-- 关联，反关联弹窗 -->
    <assObjModal @register="registerAssociatedModal" @success="updateAssociationTable" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref } from 'vue';
  import { Tabs, TabPane, Upload } from 'ant-design-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getBaseDetail } from '/@/api/demo/document';
  import assObjModal from './assObjModal.vue';

  import { createPictureDoc } from '/@/api/demo/document';

  import { getAttributeCopy, getAssociation, getBeAssociation } from './tableData';

  const emit = defineEmits(['register', 'success']);
  const { t } = useI18n();
  const UploadDragger = Upload.Dragger;
  const { createMessage } = useMessage();
  const detailActiveKey = ref<string>('1');
  const fileAssociationList = ref<any>([]);
  const haveThitObjectId = ref<string>('');
  const folderId = ref<string>('');
  const dataValue = ref<string>('');
  const fileList = ref<any>(null);
  const uploadFileText = ref<string>('');

  // 提交
  async function handleSubmit() {
    try {
      setModalProps({ confirmLoading: true });
      let fileQuality = getFieldsValue();
      let newFileList = fileAssociationList.value.map((item) => {
        return {
          OId: item.oId,
          Version: item.version,
          FileType: item.type,
        };
      });
      const formData = new FormData();
      formData.append('HaveThitObjectId', haveThitObjectId.value);
      formData.append('FolderId', folderId.value);
      formData.append('FileQuality.ThitObjectId', fileQuality.thitObjectId);
      formData.append('FileQuality.Name', fileQuality.name);
      formData.append('FileQuality.Version', fileQuality.version);
      formData.append('FileQuality.Creater', fileQuality.creater);
      formData.append('FileQuality.CreateTime', fileQuality.createTime);
      formData.append('FileQuality.FileName', fileQuality.fileName);
      formData.append('FileQuality.State', fileQuality.state);
      formData.append('FileQuality.FileType', fileQuality.fileType);
      formData.append('FileQuality.FileTypeName', fileQuality.fileTypeName);
      newFileList.forEach((item, i) => {
        formData.append(`FileAssociationList[${i}].OId`, item.OId);
        formData.append(`FileAssociationList[${i}].Version`, item.Version);
        formData.append(`FileAssociationList[${i}].FileType`, item.FileType);
      });
      formData.append('file', fileList.value);
      createPictureDoc(formData)
        .then((res) => {
          if (res) {
            createMessage.success(t('common.successText'));
            emit('success');
            handleCancel();
          }
        })
        .catch((err) => {
          createMessage.error(err.message);
          setModalProps({ confirmLoading: false });
          handleCancel();
        });
    } catch {
      setModalProps({ confirmLoading: false });
      handleCancel();
    }
  }

  // 取消
  const handleCancel = () => {
    detailActiveKey.value = '1';
    clearUpload();
    closeModal();
  };

  // 上传
  const customUpload = (e: any) => {
    uploadFileText.value = e.file.name;
    fileList.value = e.file;
    // const formData = new FormData();
    // const customFilename = e.filename || 'file';
    // if (e.filename) {
    //   formData.append(customFilename, e.file, e.file.name);
    // } else {
    //   formData.append(customFilename, e.file);
    // }
    // if (e.data) {
    //   Object.keys(e.data).forEach((key) => {
    //     const value = e.data[key];
    //     if (Array.isArray(value)) {
    //       value.forEach((item) => {
    //         formData.append(`${key}[]`, item);
    //       });
    //       return;
    //     }
    //     formData.append(key, value);
    //   });
    // }
    // fileList.value = formData.get(customFilename);
  };

  const clearUpload = () => {
    uploadFileText.value = '';
    fileList.value = null;
  };

  //关联对象
  const handleAssociated = () => {
    openAssociatedModal(true, { selectedDirKey: folderId.value });
  };

  //更新关联表格
  const updateAssociationTable = (params) => {
    fileAssociationList.value.push(params);
    console.log(fileAssociationList.value);
  };

  // 初始化弹窗
  const [register, { setModalProps, closeModal }] = useModalInner((data) => {
    resetFields();
    dataValue.value = data.fileType;
    folderId.value = data.selectedDirKey;
    setModalProps({ confirmLoading: false });
    getBaseDetail(data.fileType).then((res) => {
      setFieldsValue(res.fileQuality);
      fileAssociationList.value = res.fileAssociationList === null ? [] : res.fileAssociationList;
      haveThitObjectId.value = res.haveThitObjectId;
    });
  });

  // 属性详情
  const [registerForm, { setFieldsValue, getFieldsValue, resetFields }] = useForm({
    labelCol: { span: 4 },
    wrapperCol: { span: 20 },
    schemas: getAttributeCopy(haveThitObjectId),
    showResetButton: false,
    showSubmitButton: false,
  });
  // 关联详情
  const [registerAssociation] = useTable({
    columns: getAssociation(),
    bordered: true,
    showIndexColumn: false,
    showTableSetting: true, // 显示表格设置工具
    tableSetting: { fullScreen: true }, // 表格设置工具配置
    canResize: false,
  });
  // 被关联详情
  const [registerBeAssociation] = useTable({
    columns: getBeAssociation(),
    bordered: true,
    showIndexColumn: false,
    showTableSetting: true, // 显示表格设置工具
    tableSetting: { fullScreen: true }, // 表格设置工具配置
    canResize: false,
  });

  // 关联，反关联弹窗
  const [registerAssociatedModal, { openModal: openAssociatedModal }] = useModal();
</script>
